<template>
  <div>
    <span v-if="customTag === 'span'">{{ textToShow }}</span>
    <b v-if="customTag === 'b'">{{ textToShow }}</b>
    <p v-if="customTag === 'p'">{{ textToShow }}</p>
  </div>
</template>

<script lang="ts">
import { ref, computed, onMounted, watch } from 'vue';

export default {
  props: {
    text: {
      type: String,
      required: true
    },
    customTag: {
      type: String,
      default: 'span'
    },
    speed: {
      type: Number,
      default: 100
    },
    delay: {
      type: Number,
      default: 1500
    }
  },
  setup (props: { text: string; speed: number | undefined; } | any) {
    const currentIndex = ref(0);
    const textToShow = ref('');

    onMounted(() => {
      setTimeout(() => {
        type();
      }, props.delay);
    });

    watch(() => props.text, () => {
      textToShow.value = '';
      currentIndex.value = 0;
      setTimeout(() => {
        type();
      }, 300);
    })

    const type = () => {
      if (currentIndex.value < props.text.length) {
        textToShow.value += props.text.charAt(currentIndex.value);
        currentIndex.value++;
        setTimeout(type, props.speed);
      }
    };

    return {
      textToShow: computed(() => textToShow.value)
    };
  }
};
</script>
